package com.tt.vtg.authn.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.tt.vtg.authn.otp.OTPHandler;
import com.tt.vtg.authn.otp.common.GoogleAuthnInfo;
import com.tt.vtg.authn.otp.common.OTPMode;

@RestController
@EnableAutoConfiguration
@RequestMapping(value = "/otp")
public class TOTPController {

	@Autowired
	@Qualifier("totpHandler")
	private OTPHandler handler;

	@Autowired
	private Environment env;
	
	@RequestMapping(value = "/authn_url", method = RequestMethod.GET)
	public Map<String, String> url() {
		GoogleAuthnInfo ga = new GoogleAuthnInfo(OTPMode.totp,
				env.getProperty("otp.username"), env.getProperty("otp.secret"),
				env.getProperty("otp.issuer"), env.getProperty("otp.algorithm"),
				Integer.parseInt(env.getProperty("otp.digits")),
				Integer.parseInt(env.getProperty("totp.period")));
		Map<String, String> map = new HashMap<String, String>();
		map.put("url", ga.getUrl());
		return map;
	}

	@RequestMapping(value = "/{totp}", method = RequestMethod.GET)
	@ResponseStatus(value = HttpStatus.OK)
	public Map<String, String> validateOTP(
			@PathVariable(value = "totp") String totp,
			HttpServletResponse response) {
		boolean isValid = handler.validateOTP(totp);
		Map<String, String> map = new HashMap<String, String>();
		if (isValid) {
			map.put("result", "valid totp");
		} else {
			map.put("result", "invalid totp");
			response.setStatus(400);
		}
		return map;
	}
}
